import _ from 'underscore';
import dispatcher from 'lib/dispatcher';
import { Scope } from 'lib/scopeFactory';
import ApiFactory from 'lib/ApiFactory';

export default class DrillScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.$state = {
      loading: true,
      elements: []
    };

    // 获取关键元素列表
    this.list = ApiFactory({
      url: function () {
        return `${BlueWare.urlPrefix}/app/${BlueWare.appId}/keytransaction.json`;
      }
    });
  }

  fetch() {
    this.$state.loading = true;
    this.emit();

    this.list().fetch().then((res) => {
      this.$state.elements = (res.data || []).map((element) => {
        return {
          id: element.id,
          regexp: element.conditions['http.url'].value,
          label: element.name,
          value: element.id
        }
      });

      let first = _.first(this.$state.elements);

      if (!this.viewInstance.props.params.id && first) {
        this.viewInstance.props.history.pushState(null, `/detail/${first.id}`);
      }

      this.$state.loading = false;
      this.emit();
    });
  }

  $load() {
    this.fetch();
  }
}
